package com._430haus.FileLister;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.io.FilenameUtils;

import com._430haus.PreferenceLoader.PreferenceLoader;
import com._430haus.Video.Video;
import com._430haus.Video.VideoComparator;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class FileListerClientThread extends Thread {

	private Socket socket;

	private PrintWriter out;

	private BufferedReader in;
	
	private List<String> directories;
	
	private List<Video> videos;

	public FileListerClientThread(final Socket socket) {

		PreferenceLoader pl = PreferenceLoader.getInstance();
		this.directories = pl.getDirectoriesPreference();
		this.socket = socket;
		this.videos = new ArrayList<>();

		try {
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {

		}

	}
	
	private void handleDirectory(final File f){
		PreferenceLoader pl = PreferenceLoader.getInstance();
		List<String> fileTypes = pl.getFileTypesPreference();		
		
		final File[] listOfFiles = f.listFiles();
		for(final File file : listOfFiles){
			if(file.isDirectory()){
				handleDirectory(file);
			}else{				
				String extension = FilenameUtils.getExtension(file.getAbsolutePath());				
				if(fileTypes.contains(extension)){
					try{
						videos.add(new Video(file));
					}catch(IOException e){
						
					}
				}
			}
		}
	}

	@Override
	public void run() {
		
		for(final String directory : directories){
			handleDirectory(new File(directory));
		}
		
		Collections.sort(videos, new VideoComparator());
		
		final Gson gson = new GsonBuilder().create();
		out.print("haus(" + gson.toJson(videos) + ")");
		
		try {
			//hacky solution to ERR_CONNECTION_RESET
			Thread.sleep(300);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		out.close();

	}

}
